import React from 'react';
import './userTypeManage.less';
import {browserHistory} from 'react-router';
import { Button, Table, Modal, Pagination, message} from 'antd';
import config from '../../../config/config';
import $ from 'jquery';
const allRouter=config.router;
const token = sessionStorage.getItem('token');
class UserTypeManage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            userTypeManageList:[],//会员类型列表
            userTypeManageListEveryPage:[],//每页会员类型列表
            userTypeManageListCount:0,//会员类型列表数据条数
            pageindex:1,//当前页码
        }
    }
    componentDidMount() {
        //获取会员类型列表
        this.getDepartmentsList();
    }
    //获取会员类型列表
    getDepartmentsList() {
        let url=allRouter.patientOrigin+'/grade/list';
        //console.log(url);
        $.ajax({
            url:url,
            type: "GET",
            async: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            success:data=>{
                console.log(data);
                this.setState({
                    userTypeManageListCount:data.gread.length
                });
                if(data.code===200){
                    //给列表每一项增加索引
                    if (data.gread.length > 0) {
                        data.gread.forEach((ele, i) => {
                            ele.index= i + 1;
                            ele.discountAttribute='治疗'+ele.treatment*100+'%；外科治疗'+ele.adjuvanttherapy*100+'%；中药'+ele.chinesemedicine*100;
                            ele.discountAttribute+='%；西药'+ele.westernmedicine*100+'%；挂号'+ele.registered*100+'%；小儿推拿'+ele.infantiletuina*100;
                            ele.discountAttribute+='%；针灸/拔罐/按摩'+ele.acupuncture*100+'%；女性护理'+ele.femininecare*100+'%；材料费'+ele.costofrawmaterials*100;
                            ele.discountAttribute+='%；其他收费'+ele.others*100+'%';
                        });
                    }
                    //console.log(data);
                    this.setState({userTypeManageList:data.gread},()=>{
                        // console.log(this.state.userTypeManageList);
                        //将原来的数组复制给一个空数组
                        let allList=[];
                        for(let i=0;i<data.gread.length;i++){
                            allList[i]=data.gread[i];
                        }
                        let pageData=allList.splice(10*(this.state.pageindex-1),10);
                        // console.log(pageData);
                        this.setState({
                            userTypeManageListEveryPage:pageData
                        })

                    })
                }else{
                    console.log("获取会员类型列表出错");
                }
            },
            error:err=>{
                console.log(err);
            }
        });
    }
    //分页
    changePage(pageindex) {
        //console.log(pageindex);
        this.setState({
            pageindex
        },()=>{
            let allList=[];
            for(let i=0;i<this.state.userTypeManageList.length;i++){
                allList[i]=this.state.userTypeManageList[i];
            }
            let pageData=allList.splice(10*(this.state.pageindex-1),10);
            this.setState({
                userTypeManageListEveryPage:pageData
            })
        });
    }

    //删除会员类型数据
    deleteUserType(record) {
        Modal.confirm({
            title: '删除会员类型',
            content: '确认删除该会员类型数据吗?',
            cancelText:'取消',
            okText:'确定',
            onCancel: () => { message.info('取消删除该会员类型数据') },
            onOk: () => {
                //发送Ajax请求
                //未找到此路径
                let url=allRouter.patientOrigin+'/grade/delete';
                $.ajax({
                    url:url,
                    type: "post",
                    async: true,
                    headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                    data:{
                        id:record._id
                    },
                    success:data=>{
                        if(data.code===200){
                            this.getDepartmentsList();
                        }else{
                            message.info('删除失败');
                        }
                    },
                    error:err=>{
                        console.log(err);
                    }
                });
            }
        })
    }
    //编辑会员类型状态
    editUserTypeState(recode) {
       // console.log(recode);
        let currentState=recode.state;
        if(currentState==="启用"){
            currentState="禁用"
        }else if(currentState==="禁用"){
            currentState="启用"
        }
        let url=allRouter.patientOrigin+'/grade/update';

        $.ajax({
            url:url,
            type: "POST",
            async: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            data:{
                id:recode._id,
                state:currentState,
            },
            success:data=>{
                console.log(data);
                if(data.code===200){
                    this.getDepartmentsList();
                }else{
                    message.info('更改状态错误');
                }
            },
            error:err=>{
                console.log(err);
            }
        });
    }

    render() {
        const columns = [
            {
                title: '序号',
                dataIndex: 'index',
                width: 50,
            },
            {
                title: '会员类型名称',
                dataIndex: 'name',
                width: 50,
           }, {
                title: '折扣属性',
                dataIndex: 'discountAttribute',
                width: 280,
            },{
                title: '状态',
                dataIndex: 'state',
                width: 50,
                render:(text,recode)=> <Button onClick={this.editUserTypeState.bind(this,recode)} type={text=='启用'?'primary':text=='禁用'?'danger':''}>{text=='启用'?'已启用，点击可禁用':text=='禁用'?'已禁用，点击可启用':''}</Button>
            }, {
                title: '操作',
                width: 150,
                render: (text, record) => (
                    <div>
                        <Button onClick={() => { browserHistory.push('addUserTypeForm/'+record._id)}} type="primary" >编辑</Button>
                        <Button onClick={this.deleteUserType.bind(this, record)}  type="danger">删除</Button>
                    </div>
                )
            }
        ];
        return (
            <div className="container">
                <div className="store-manage-content">
                    {/*增加按钮*/}
                    <div className="storeAdd">
                        <Button onClick={() => { browserHistory.push('addUserTypeForm/0') }}  type="primary"> <img src={require('../../../../images/add.png')} alt=""/>新增会员类型</Button>
                    </div>
                    {/*会员类型列表 */}
                    <div className='all-roles-table'>
                        <Table
                            rowKey="index"
                            columns={columns}
                            dataSource={this.state.userTypeManageListEveryPage}
                            pagination={false}
                            bordered
                        />
                    </div>
                    {/*分页*/}
                    <div className="pagination">
                        <Pagination current={this.state.pageindex} showQuickJumper total={this.state.userTypeManageListCount || 1} defaultPageSize={10} onChange={this.changePage.bind(this)} />
                    </div>
                </div>
            </div>
        )
    }
}
export default UserTypeManage;